package com.example.ai.controller;

import com.example.ai.security.JwtTokenProvider;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : zhayh
 * @date : 2021-4-17 14:07
 * @description :
 */

@RestController
@RequestMapping("/api")
public class LoginApi {
    private AuthenticationManagerBuilder authenticationManagerBuilder;
    private JwtTokenProvider tokenProvider;

    public LoginApi(AuthenticationManagerBuilder authenticationManagerBuilder, JwtTokenProvider tokenProvider) {
        this.authenticationManagerBuilder = authenticationManagerBuilder;
        this.tokenProvider = tokenProvider;
    }

    /**
     * 使用JwtTokenProvider验证用户登录信息
     * @param login 用户名
     * @param password 密码
     * @return ResponseEntity对象
     */
    @PostMapping("/login")
    public ResponseEntity loginJwt(String login, String password) {
        // 1. 根据用户名和密码构建SpringSecurity身份校验的数据对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(login, password);

        try {
            Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
            String userToken = tokenProvider.createToken(authentication);
            return ResponseEntity.ok(userToken);

        } catch (Exception e) {
            return ResponseEntity.status(401).body("用户名或密码错误");
        }
    }
}
